const express = require('express');
const app = express();
app.listen(3000, () => { console.log('服务器已开启') });

//引入mysql模块
const mysql = require('mysql');

// 创建mysql链接
let con = mysql.createConnection({
    host: 'localhost',
    port: 3306,
    user: 'root',
    password: 'root',
    database: 'demo01'
})

//链接mysql
con.connect();

//接惨
app.use(express.urlencoded({ extended: false }));
app.use(express.json());

//注册
app.post('/register', (req, res) => {
    //接惨获取用户的数据
    let { username, password } = req.body;
    console.log(username, password);

    //注册数据库逻辑
    let sql = `SELECT * FROM aemo1 WHERE username = '${username}'`;
    con.query(sql, (err, result) => {
        //判断err是否有错误信息
        if (err) {
            res.send({ code: 404, msg: err })
            return;
        }

        //判断数据库内是否有用户输入的,如果查询到则大于1，查询错误则出错
        if (result.length > 0) {
            res.send({ code: 400, msg: '用户名已存在' });
            return;
        }

        //如果用户不存在则添加到数据库内
        let sql = `INSERT INTO aemo1 (username,password) VALUES ('${username}','${password}')`;
        con.query(sql, (err, result) => {
            //判断错误信息
            if (err) {
                res.send({ code: '400', msg: err })
                return;
            }

            //如果注册成功id属性往后加一个，否则失败
            if (result.insertId > 0) {
                res.send({ code: '200', msg: '注册成功' });
            } else {
                res.send({ code: '400', msg: '注册失败' })
            }
            console.log(result);
        })
    })
})